﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Consult
{
    [XmlRoot]
    public class ApplicationSettings
    {
        private static ApplicationSettings _instance;
        private ApplicationSettings() { }
        [XmlElement]
        public static ApplicationSettings Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ApplicationSettings();
                    Deserialize();
                }
                return _instance;
            }
        }

        [XmlAttribute]
        public string CountryName { get; set; }
        [XmlArray]
        public string[] PrevCountries { get; set; }
        [XmlAttribute]
        public string CityName { get; set; }
        [XmlArray]
        public string[] PrevCities { get; set; }
        [XmlAttribute]
        public string TypeName { get; set; }
        [XmlArray]
        public string[] PrevTypes { get; set; }
        [XmlAttribute]
        public string OfficeName { get; set; }
        [XmlArray]
        public string[] PrevOffices { get; set; }
        [XmlAttribute]
        public int Timeout { get; set; }
        [XmlAttribute]
        public TypeOfParser TypeOfParser { get; set; }

        private static string SettingsFilePath
        {
            get { return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Configuration.xml"; }
        }
        public static void Serialize()
        {
            using (TextWriter writer = new StreamWriter(SettingsFilePath))
            {
                var serializer = new XmlSerializer(typeof(ApplicationSettings));
                serializer.Serialize(writer, Instance);
            }
        }
        public static void Deserialize()
        {
            if (!File.Exists(SettingsFilePath))
            {
                LoadDefaults();
                return;
            }
            try
            {
                using (var reader = XmlReader.Create(SettingsFilePath))
                {
                    var serializer = new XmlSerializer(typeof(ApplicationSettings));
                    if (serializer.CanDeserialize(reader))
                    {
                        _instance = serializer.Deserialize(reader) as ApplicationSettings;
                    }
                }
            }
            catch (Exception)
            {
                LoadDefaults();
            }
        }
        private static void LoadDefaults()
        {
            Instance.CountryName = "Беларусь";
            Instance.CityName = "Гродно";
            Instance.TypeName = "Виза Schengen";
            Instance.OfficeName = "Гродно";
            Instance.TypeOfParser = TypeOfParser.SchengenVisa;
            Instance.Timeout = 60;
        }

    }
}
